<template>
  <view class="container">
    <view class="navbar">
      <view class="fixed-content">
        <!-- 状态栏高度 -->
        <view
          :style="{ height: statusBarHeight + 'px' }"
          class="statusBar"
        ></view>
        <!-- <view class="statusBar" style="height: var(--status-bar-height);"> -->
        <!-- 导航栏高度 -->
        <view class="bar-content" :style="{ height: getNavBarHeight() + 'px' }">
          <slot>
            <image @tap="navigateBack()" class="nav-left" mode=""></image>
            <view class="nav-title">登录</view>
          </slot>
        </view>
      </view>
      <!-- 占位高度，状态栏高度+导航栏高度，父组件就不需要计算导航栏高度 -->
      <view
        :style="{ height: statusBarHeight + getNavBarHeight() + 'px' }"
      ></view>
    </view>
    <u-form ref="form" :model="form" :rules="rules">
      <u-form-item label="手机号" label-width="100rpx" prop="phone">
        <u-input
          v-model="form.phone"
          type="number"
          placeholder="请输入手机号"
        />
      </u-form-item>
      <u-form-item label="验证码" label-width="100rpx" prop="code">
        <u-input v-model="form.code" type="number" placeholder="请输入验证码" />
        <u-button
        size="mini"
          slot="right"
          :plain="true"
          style="width: 160rpx; margin-left: 10rpx"
          @click="getCode"
          >{{ showGetCode ? "获取验证码" : countdown + "秒" }}</u-button
        >
      </u-form-item>
    </u-form>
    <u-button class="login" type="primary" @click="submit">登录</u-button>
  </view>
</template>
 
<script>
import api from "@/common/utils/api"; //接口
import request from "@/router/axios";

export default {
  data() {
    return {
      form: {
        phone: "",
        code: "",
      },
      rules: {
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur",
          },
        ],
      },
      countdown: 60, // 验证码倒计时
      showGetCode: true,
      statusBarHeight: 0,
    };
  },
  created() {
    uni.getSystemInfo({
      success: function (info) {
        console.log("Status bar height: " + info.statusBarHeight);
        this.statusBarHeight = info.statusBarHeight;
      },
    });
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.form.setRules(this.rules);
  },
  methods: {
    // 获取状态栏高度
    geStatusBarHeight() {
      return uni.getSystemInfoSync()["statusBarHeight"];
    },
    // 获取导航栏高度
    getNavBarHeight() {
      // #ifdef MP-WEIXIN
      let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
      // 导航栏高度 = 胶囊高度 + 上间距 + 下间距 + 微调	（menuButtonInfo.top - uni.getSystemInfoSync()['statusBarHeight'] = 上间距）
      // let navbarHeight =
      //   menuButtonInfo.height +
      //   (menuButtonInfo.top - uni.getSystemInfoSync()["statusBarHeight"]) * 2 +
      //   2;
      // #endif
      // #ifdef APP-PLUS || H5
      let navbarHeight = 44;
      // #endif
      return navbarHeight;
    },
    navigateBack() {
      uni.navigateBack();
    },
    // 获取验证码
    getCode() {
      // 这里应该发送请求到后端获取验证码，并处理相关业务逻辑
      console.log("获取验证码逻辑");
      if (this.showGetCode) {
        var reg = /^1[3456789]\d{9}$/;
        if (reg.test(this.form.phone)) {
          // api.smsCode({ phone: this.form.phone }).then((res) => {
          //   if (res.success) {
          //     uni.showToast({
          //       title: "发送成功！",
          //       icon: "none",
          //     });
          //     this.countdown = 60;
          //     const interval = setInterval(() => {
          //       if (this.countdown > 0) {
          //         this.showGetCode = false;
          //         this.countdown--;
          //       } else {
          //         clearInterval(interval);
          //         this.countdown = 60;
          //         this.showGetCode = true;
          //       }
          //     }, 1000);
          //   }
          //   uni.hideLoading();
          // });
          uni.showLoading();
          request({
            url: "http://124.222.0.192:9999/app/send/smscode",
            method: "post",
            data: { phone: this.form.phone },
          })
            .then((res) => {
              uni.hideLoading();
              console.log("res>>>>>>>>>>>>>>>>>", res);
              if (res.data.success) {
                uni.showToast({
                  title: "发送成功！",
                  icon: "none",
                });
                this.countdown = 60;
                const interval = setInterval(() => {
                  if (this.countdown > 0) {
                    this.showGetCode = false;
                    this.countdown--;
                  } else {
                    clearInterval(interval);
                    this.countdown = 60;
                    this.showGetCode = true;
                  }
                }, 1000);
              } else {
                uni.showToast({
                  title: res.data.msg,
                  icon: "none",
                });
              }
            })
            .catch((e) => {
              uni.hideLoading();
              console.log("e>>>>>>>>>>>>>>>>>>>>>>>>>>>>", e);
              uni.showToast({
                title: "获取失败",
                icon: "none",
              });
            });
        } else {
          uni.showToast({
            title: "手机号码格式不正确",
            icon: "none",
          });
        }
      }
    },

    submit() {
      // 表单验证
      // uni.setStorageSync("phone", "15055009541");
      // var userInfo = {
      //   phone: "15055009541",
      //   code: "123456",
      // };
      // uni.setStorageSync("userInfo", userInfo);
      // uni.setStorageSync("userInfo", userInfo);
      // uni.switchTab({
      //   url: "/pages/mall/index",
      // });
      // return;
      const validRes = this.$refs.form.validate();
      if (validRes) {
        uni.showLoading();
        // api
        //   .login({ phone: this.form.phone, smsCode: this.form.code })
        //   .then((res) => {
        //     if (res.success) {
        //       var userInfo = {
        //         phone: this.form.phone,
        //         code: this.form.code,
        //       };
        //       console.log("userInfo：", userInfo);
        //       uni.setStorageSync("phone", this.form.phone);
        //       uni.setStorageSync("userInfo", userInfo);
        //       uni.switchTab({
        //         url: "/pages/mall/index",
        //       });
        //     } else {
        //       uni.showToast({
        //         title: "登录失败",
        //         icon: "none",
        //       });
        //     }
        //   });
        request({
          url: "http://124.222.0.192:9999/app/login",
          method: "post",
          data: { phone: this.form.phone, smsCode: this.form.code },
        })
          .then((res) => {
            console.log("res>>>>>>>>>>>>>>>>>>>>>>>>>>>>", res);
            if (res.data.success) {
              var userInfo = {
                phone: this.form.phone,
                code: this.form.code,
              };
              console.log("userInfo：", userInfo);
              uni.setStorageSync("phone", this.form.phone);
              uni.setStorageSync("userInfo", userInfo);
              uni.switchTab({
                url: "/pages/mall/index",
              });
            } else {
              uni.showToast({
                title: res.data.msg,
                icon: "none",
              });
            }
          })
          .catch((e) => {
            console.log("e>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", e);
            uni.showToast({
              title: "登录失败",
              icon: "none",
            });
          });
        uni.hideLoading();
      } else {
        console.log("表单验证失败");
      }
    },
    login(credentials) {
      // 这里使用模拟的API请求进行登录
      // 实际项目中，你需要替换为真实的登录API
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true, data: {} }); // 模拟登录成功
          // 实际项目中，根据服务器响应进行处理
        }, 1000);
      });
    },
  },
};
</script>

<style scoped lang="scss" >
.container {
  padding: 100rpx 80rpx;
}
.login {
  margin-top: 30rpx;
}
.navbar {
  .fixed-content {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    padding: 0 24rpx;
    z-index: 1996;
    .bar-content {
      display: flex;
      align-items: center;
      position: relative;
      .nav-left {
        width: 22px;
        height: 22px;
        position: absolute;
        z-index: 2;
        top: 50%;
        transform: translateY(-50%);
      }
      .nav-title {
        font-weight: bold;
        font-size: 16px;
        width: 100%;
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        text-align: center;
      }
    }
  }
}
</style>